package com.scau.databaseexam.controllers;

import com.scau.databaseexam.DAO.UserDao;
import com.scau.databaseexam.beans.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.Map;

@Controller
public class RegisterController {

    @Value("${web.upload-path}")
    private String uploadPath;

    @Autowired
    UserDao userDao;

    @RequestMapping("/register")
    public String toRegisterPage(){
        return "register";
    }

    @RequestMapping("/user/register")
    public String registerBack(User user, HttpServletRequest request, Map<String,String> map, HttpSession session){

        System.out.println(user.toString());
        //判单数据库是否存在重复id
        //判断两次密码是否相同
        User register = userDao.selectUser(user.getId());
        String confirm = request.getParameter("confirm");
        if(register != null){
            map.put("msg","id exist!");

        }else if(user.getPassword().equals(confirm)) {
            //存入数据库
            userDao.insertUser(user);
            //创建用户文件夹
            String filePath=uploadPath+"\\"+user.getId();
            System.out.println("filePath Creat:" + filePath);
            File dir = new File(filePath);
            if(!dir.exists()){
                dir.mkdir();
            }
            return "login";

        }else {

            map.put("msg","password is not same");
        }
        session.setAttribute("msg",map);
        return "register";

    }

}
